package com.jt.demos;

import redis.clients.jedis.Jedis;

/**
 * 秒杀队列演示
 * 算法: 先进先出(FIFO)--公平性
 * 描述逻辑: 将商品抢购信息先写到redis(队列形式)
 *          redis是内存数据库,要比写进mysql数据库快
 */
public class SecondKillDemo01 {
    //商品抢购 入队操作
    static void enque(String msg){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        jedis.lpush("queue", msg);
        jedis.close();
    }
    //商品异步出队(基于返回值,生成订单,扣减库存)
    static String deque(){
        Jedis jedis = new Jedis("192.168.126.129",6379);
        String result = jedis.rpop("queue");
        jedis.close();
        return result;
    }
    public static void main(String[] args) {
        new Thread(){
            @Override
            public void run() {
                //1. 多次抢购
                for (int i=1;i<=10;i++){
                    enque(String.valueOf(i));
                    try { Thread.sleep(100); } catch (Exception e) { e.printStackTrace(); }
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                //2. 提取信息
                for (;;){
                    String msg = deque();
                    if (msg==null)continue;
                    System.out.print(msg);
                }
            }
        }.start();

    }
}
